<template>
  <el-dialog
    append-to-body
    :before-close="handleClose"
    center
    :show-close="true"
    :visible.sync="dialogUploadVisible"
    width="620px"
  >
    <div slot="title" class="dialog-title">
      <div style="display: flex; align-items: center">
        <el-upload
          ref="my_upload"
          action=""
          :before-upload="beforeUpload"
          class="upload-demo"
          :http-request="handleUpload"
          :show-file-list="false"
        >
          <el-button size="small" type="success">点击上传</el-button>
        </el-upload>
        <vab-icon
          icon="refresh-line"
          style="margin-left: 20px"
          @click="fetchData"
        />
      </div>
    </div>
    <span style="padding-top: 0">
      <div class="attachment-list-region pull-right">
        <el-tabs v-model="activeName">
          <el-tab-pane label="本地图片" name="local">
            <div v-loading="listLoading" class="rc-upload-materials clearfix">
              <ul class="image-list">
                <li
                  v-for="(item, index) in imgList"
                  :key="index + 'imgList'"
                  class="image-item"
                  @click="chooseImg(index)"
                >
                  <div
                    class="image-box"
                    :style="{ backgroundImage: 'url(' + item.fill_url + ')' }"
                  />
                  <div class="image-meta">
                    {{ item.imagewidth }}*{{ item.imageheight }}
                  </div>
                  <div class="image-title-wrap" title="message.png">
                    <p class="image-title">{{ item.filename }}</p>
                    <p class="image-title-ext" />
                  </div>

                  <div
                    v-for="(val, i) in chooseList"
                    v-show="index == val"
                    :key="index + '' + i"
                    class="attachment-selected"
                  >
                    <i class="selected-index">{{ i + 1 }}</i>
                  </div>
                </li>
              </ul>
            </div>

            <el-pagination
              background
              :current-page="queryForm.pageNo"
              :layout="layout"
              :page-size="queryForm.pageSize"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            />
          </el-tab-pane>
          <el-tab-pane label="网络图片" name="internet">
            <el-alert
              :closable="false"
              title="网络图片指的是直接使用链接而不是下载到服务器, 如需要同时添加多张请使用 #$% 符号隔开(防止链接有特殊字符)"
              type="warning"
            />
            <el-form
              ref="internet-form"
              label-width="80px"
              :model="internetForm"
            >
              <el-form-item
                label="图片链接"
                prop="url"
                :rules="[
                  {
                    required: true,
                    trigger: 'blur',
                    message: '请输入图片链接',
                  },
                ]"
              >
                <el-input v-model="internetForm.url" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </div>
    </span>
    <div slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="chooseSure">
        确认
      </el-button>
    </div>
  </el-dialog>
</template>
<script>
  import { getList, uploadImage } from '@/api/attachment'
  export default {
    name: 'UploadImage',
    props: {
      maxcount: {
        type: Number,
        default: 1,
      },
      nowcount: {
        type: Number,
        default: 0,
      },
    },
    data() {
      return {
        dialogUploadVisible: false,
        listLoading: false,
        activeName: 'local',
        chooseList: [],
        imgList: [],
        total: 0,
        layout: 'total, prev, pager, next, jumper',
        queryForm: {
          pageNo: 1,
          pageSize: 20,
        },
        internetForm: {
          url: '',
        },
      }
    },
    methods: {
      showLoad() {
        if (this.imgList.length == 0) {
          this.fetchData()
        }
        this.dialogUploadVisible = true
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        const { list, total } = data
        this.imgList = list
        this.total = total
        this.listLoading = false
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNo = val
        this.fetchData()
      },
      /** 选择每一张图片 高亮 */
      chooseImg(index) {
        var getIndex = this.chooseList.indexOf(index)
        if (getIndex > -1) {
          this.chooseList.splice(getIndex, 1)
        } else {
          if (this.maxcount == 1) {
            this.chooseList.splice(0, this.chooseList.length)
            this.chooseList.push(index)
          } else {
            if (
              this.chooseList.length + this.nowcount < this.maxcount ||
              this.maxcount == 0
            ) {
              this.chooseList.push(index)
            } else {
              this.$baseMessage(
                '最多只能选择' + this.maxcount + '张图片',
                'error'
              )
            }
          }
        }
      },
      chooseSure() {
        if (this.activeName == 'local') {
          if (this.chooseList.length > 0) {
            let res = []
            this.chooseList.forEach((v) => {
              const imgItem = this.imgList[v].fill_url
              res.push(imgItem)
            })
            this.$emit('uploadChoose', res)
            this.chooseList.splice(0, this.chooseList.length)
            this.dialogUploadVisible = false
          }
        } else {
          this.$refs['internet-form'].validate(async (valid) => {
            if (valid) {
              let res = this.internetForm.url.split('#$%')
              if (this.maxcount != 0) {
                res.splice(this.maxcount - this.nowcount, res.length)
              }
              this.$emit('uploadChoose', res)
              this.dialogUploadVisible = false
            }
          })
        }
      },
      /** 关闭窗口 */
      handleClose(done) {
        this.chooseList.splice(0, this.chooseList.length)
        done()
      },
      handleUpload(params) {
        const file = params.file
        const form = new FormData()
        // 文件对象
        form.append('file', file)
        uploadImage(form).then((res) => {
          if (res.code == 0) {
            this.$baseMessage('上传成功', 'success')
            this.fetchData()
          }
        })
        this.$refs['my_upload'].clearFiles()
      },
      beforeUpload(file) {
        const isJPG =
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/gif'
        const isLt2M = file.size / 1024 / 1024 < 3

        if (!isJPG) {
          this.$baseMessage('上传图片只能是 JPG PNG GIF 格式!', 'error')
        }
        if (!isLt2M) {
          this.$baseMessage('上传图片大小不能超过 3MB!', 'error')
        }

        return isJPG && isLt2M
      },
    },
  }
</script>
<style>
  .el-dialog--center .el-dialog__body {
    padding-top: 0px;
  }
  .dialog-title {
    text-align: left;
  }
  .attachment-list-region {
    width: 580px;
  }
  .rc-upload-materials {
    position: relative;
    width: 580px;
    padding: 0;
    overflow: hidden;
  }
  .rc-upload .pull-right {
    float: right;
  }

  .rc-upload-materials li,
  .rc-upload-materials ul {
    padding: 0;
    margin: 0;
    list-style: none;
  }

  .rc-upload-materials .image-list .image-item {
    position: relative;
    float: left;
    width: 105px;
    height: 105px;
    margin-right: 10px;
    margin-bottom: 30px;
    cursor: pointer;
  }

  .rc-upload-materials .image-list .image-box {
    width: 105px;
    height: 105px;
    background: #ccc;
    background-position: 50% 50%;
    background-size: cover;
  }

  .rc-upload-materials .image-list .image-meta {
    position: absolute;
    bottom: 0;
    width: 105px;
    height: 25px;
    font-size: 12px;
    line-height: 25px;
    color: #fff;
    text-align: center;
    background: rgba(0, 0, 0, 0.2);
  }

  .rc-upload-materials .image-list .image-title-wrap {
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: -moz-box;
    display: flex;
  }

  .rc-upload-materials .image-list .image-title {
    width: 105px;
    height: 16px;
    margin: 0;
    overflow: hidden;
    line-height: 16px;
    text-align: center;
  }

  .rc-upload-materials .attachment-selected {
    position: absolute;
    top: 0;
    left: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    border: 2px solid #07d;
  }

  .rc-upload-materials .attachment-selected i.selected-index {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 2;
    width: 13px;
    height: 15px;
    font-family: arial;
    font-size: 12px;
    font-style: normal;
    color: #fff;
    text-align: center;
  }

  .rc-upload-materials .attachment-selected:after {
    bottom: auto;
  }

  .rc-upload-materials .attachment-selected:after {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    display: block;
    content: ' ';
    border: 14px solid #07d;
    border-bottom-color: transparent;
    border-left-color: transparent;
  }

  .rc-upload-materials .attachment-selected:after {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    display: block;
    content: ' ';
    border: 14px solid #07d;
    border-bottom-color: transparent;
    border-left-color: transparent;
  }
</style>
